package com.tanhua.sso.service;

import com.tanhua.sso.config.AliyunSMSConfig;
import com.tanhua.sso.util.SmsUtil;
import com.tanhua.sso.vo.ErrorResult;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.time.Duration;

@Service
@Slf4j
public class SmsService {
    private final RedisTemplate<String, String> redisTemplate;
    private final AliyunSMSConfig aliyunSMSConfig;

    public SmsService(AliyunSMSConfig aliyunSMSConfig, RedisTemplate<String, String> redisTemplate) {
        this.aliyunSMSConfig = aliyunSMSConfig;
        this.redisTemplate = redisTemplate;
    }

    private final SmsUtil smsUtil = new SmsUtil();

    /**
     * 发送验证码短信,并在发送完成验证码短信后,需要将验证码保存到Redis中
     *
     * @param phone 目标手机号
     * @return 发送成功:null,发送失败:ErrorResult(错误代码+描述信息)
     */
    public ErrorResult sendCheckCode(String phone) {
        String redisKey = "CHECK_CODE_" + phone;
        // 先判断发送给该手机号的验证码是否还未失效(redis中有没有)
        if (Boolean.TRUE.equals(this.redisTemplate.hasKey(redisKey))) {
            String msg = "上一次发送的验证码还未失效";
            return ErrorResult.builder().errCode("000010").errMessage(msg).build();
        }

        // 程序能走到这里,说明验证码失效了,则重新发送
        String code = smsUtil.sendSms(phone, 6, aliyunSMSConfig);

        // 查看发送结果,如果失败,则返回错误代码和描述信息
        if (StringUtils.isEmpty(code)) {
            String msg = "阿里云发送验证码短信失败";
            return ErrorResult.builder().errCode("000000").errMessage(msg).build();
        }

        // 程序能走到这里,说明短信发送成功
        // 那就将验证码保存到Redis中,设置有效期为5min，并返回null
        this.redisTemplate.opsForValue().set(redisKey, code, Duration.ofMinutes(5));
        return null;
    }
}
